package com.dongwu.manager.service.impl;

import com.dongwu.common.service.impl.BaseServiceImpl;
import com.dongwu.manager.dao.UserInfoDao;
import com.dongwu.manager.entity.UserInfo;
import com.dongwu.manager.service.UserInfoService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Base64;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends BaseServiceImpl<UserInfo, String> implements UserInfoService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Override
    public void saveUserInfo(Map<String, Object> userInfoMap) throws IOException, URISyntaxException {
        UserInfo userInfo = new UserInfo();
        JSONObject jsonObject = new JSONObject(userInfoMap);
        if (!jsonObject.has("errcode")) {
            UserInfo ui = userInfoDao.findByOpenid(jsonObject.getString("openid"));
            if(ui == null){
                // 用户的标识
                userInfo.setOpenid(jsonObject.getString("openid"));
                Base64.Encoder encoder = Base64.getEncoder();
                // 昵称
                userInfo.setNickname(new String(encoder.encodeToString(jsonObject.getString("nickname").getBytes("UTF-8"))));
                // 用户的性别（1是男性，2是女性，0是未知）
                userInfo.setSex(jsonObject.getInt("sex"));
                // 用户所在国家
                userInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                userInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                userInfo.setCity(jsonObject.getString("city"));
                // 用户的语言，简体中文为zh_CN
                userInfo.setLanguage(jsonObject.getString("language"));
                // 用户头像
                userInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
                userInfoDao.save(userInfo);
            }
        }
    }
}
